<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="商品指标" name="first">
        <div>
          <el-row>
            店铺:
            <el-select v-model="goodsUploadData.goodsStoreId" filterable placeholder="请选择店铺" clearable @change="goodsStoreIdChange">
              <el-option
                v-for="item in storeList"
                :key="item.id"
                :label="item.storeAbbr"
                :value="item.id">
              </el-option>
            </el-select>
          </el-row>

          <el-row style="margin-top: 10px">
            日期:
            <el-date-picker
              v-model="goodsUploadData.goodsSelectDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择日期">
            </el-date-picker>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-upload
              class="upload-demo"
              :headers="{
          'Authorization': 'Bearer ' + gainGetToken()
        }"
              :disabled="goodsUploadData.goodsStoreId===null||goodsUploadData.goodsSelectDate==null"
              ref="goodsUpload"
              :auto-upload="false"
              :action=goodsUploadAction
              :data="goodsUploadData"
              :on-change="handleGoodsChange"
              :on-progress="handleGoodsLoading"
              :on-success="handleGoodsUploadMessage"
              :file-list="goodsFileList"
              :limit="1"
              drag>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将<span class="font-color">商品指标</span>文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="全站指标" name="second">
        <div>
          <el-row>
            店铺:
            <el-select v-model="wholeUploadData.wholeStoreId" filterable placeholder="请选择店铺" clearable @change="wholeStoreIdChange">
              <el-option
                v-for="item in storeList"
                :key="item.id"
                :label="item.storeAbbr"
                :value="item.id">
              </el-option>
            </el-select>
          </el-row>

          <el-row style="margin-top: 10px">
            日期:
            <el-date-picker
              v-model="wholeUploadData.wholeSelectDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择日期">
            </el-date-picker>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-upload
              class="upload-demo"
              :headers="{
          'Authorization': 'Bearer ' + gainGetToken()
        }"
              :disabled="wholeUploadData.wholeStoreId===null||wholeUploadData.wholeSelectDate==null"
              accept=".xlsx, .xls, .csv"
              ref="wholeUpload"
              :auto-upload="false"
              :action=wholeUploadAction
              :data="wholeUploadData"
              :on-change="handleWholeChange"
              :on-progress="handleWholeLoading"
              :on-success="handleWholeUploadMessage"
              :file-list="wholeFileList"
              :limit="1"
              drag>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将<span class="font-color">全站指标</span>文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="无界指标" name="third">
        <div>
          <el-row>
            店铺:
            <el-select v-model="unUploadData.unStoreId" filterable placeholder="请选择店铺" clearable @change="unStoreIdChange">
              <el-option
                v-for="item in storeList"
                :key="item.id"
                :label="item.storeAbbr"
                :value="item.id">
              </el-option>
            </el-select>
          </el-row>

          <el-row style="margin-top: 10px">
            日期:
            <el-date-picker
              v-model="unUploadData.unSelectDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择日期">
            </el-date-picker>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-upload
              class="upload-demo"
              :headers="{
          'Authorization': 'Bearer ' + gainGetToken()
        }"
              :disabled="unUploadData.unStoreId===null||unUploadData.unSelectDate==null"
              accept=".xlsx, .xls, .csv"
              ref="unUpload"
              :auto-upload="false"
              :action=unUploadAction
              :data="unUploadData"
              :on-change="handleUnChange"
              :on-progress="handleUnLoading"
              :on-success="handleUnUploadMessage"
              :file-list="unFileList"
              :limit="1"
              drag>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将<span class="font-color">无界指标</span>文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="上新日期" name="fourth">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          @click="handleNoUpNewDateExport"
        >导出无上新日期数据</el-button>

        <el-upload
          class="upload-demo"
          :headers="{
          'Authorization': 'Bearer ' + gainGetToken()
          }"
          ref="upNewDateUpload"
          :action=upNewDateAction
          :on-success="handleUpNewDateUploadMessage"
          :on-progress="handleUnLoading"
          multiple
          :limit="1"
          drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将<span class="font-color">上新日期</span>文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="商品标签" name="fifth">

        <el-upload
          class="upload-demo"
          :headers="{
          'Authorization': 'Bearer ' + gainGetToken()
          }"
          ref="goodsLabelUpload"
          :action=goodsLabelAction
          :on-success="handleGoodsLabelUploadMessage"
          :on-progress="handleGoodsLabelLoading"
          multiple
          :limit="1"
          drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将<span class="font-color">商品标签</span>文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import {getStoreMgmt} from "@/api/business/storeMgmt";
import {exportNoUpNewDateExcel} from "@/api/business/goodsIndicators";
import SparkMD5 from "spark-md5";
import {getInfo} from "@/api/login";
import {getConfigByType, getConfigDetailByType} from "@/api/business/operationStoreConfig";

export default {
  name: "IndicatorsUpload",
  data() {
    return{
      activeName: 'first',
      //店铺列表
      storeList: [],
      //上传加载
      uploadLoad: null,
      //商品指标上传路径
      goodsUploadAction: process.env.VUE_APP_BASE_API+"/business/goodsIndicators/uploadData",
      goodsFileList: [],
      goodsStoreIndex:0,
      //商品指标上传数据
      goodsUploadData: {goodsStoreId: null, goodsSelectDate: null, goodsFileHash: null},
      //全站推指标上传路径
      wholeUploadAction: process.env.VUE_APP_BASE_API+"/business/wholeStationIndicators/uploadData",
      wholeFileList: [],
      wholeStoreIndex:0,
      //全站推指标上传数据
      wholeUploadData: {wholeStoreId: null, wholeSelectDate: null, wholeFileHash: null},
      //无界指标上传路径
      unUploadAction: process.env.VUE_APP_BASE_API+"/business/unboundedIndicators/uploadData",
      unFileList: [],
      unStoreIndex:0,
      //无界指标上传数据
      unUploadData: {unStoreId: null, unSelectDate: null, unFileHash: null},
      //上新日期文件上传路径
      upNewDateAction:process.env.VUE_APP_BASE_API+"/business/upDate/uploadUpNewDate",
      //3C事业部固定店铺列表
      storeList3C: [
        {
          id: "01JKRRSM71DN12T2PV0QTQ1SPP",
          storeName:"呈讯旗舰店",
          storeAbbr: "呈讯*天猫"
        },
        {
          id: "01JKRRSM7139FTSHHSYCMDPSY4",
          storeName:"华鲁搜途旗舰店",
          storeAbbr: "华鲁搜途*天猫"
        },
        {
          id: "01JKRRSM73S19MKWBM7Y7D075K",
          storeName:"画萌文教用具旗舰店",
          storeAbbr: "画萌*天猫"
        },
        {
          id: "01JKRRSM70JKRHAZMYXDH1Z8SQ",
          storeName:"九变定制旗舰店",
          storeAbbr: "九变*天猫"
        },
        {
          id: "01JKRRSM72DYKS4ARFR3WFWSHA",
          storeName:"九鼎铎金旗舰店",
          storeAbbr: "九鼎铎金*天猫"
        },
        {
          id: "01JKRRSM71N0TKMRGHDCN0EEAN",
          storeName:"美格鸿旗舰店",
          storeAbbr: "美格鸿*天猫"
        },
        {
          id: "01JKRRSM71GG8N3PXTB3HNR5YD",
          storeName:"派依倍旗舰店",
          storeAbbr: "派依倍*天猫"
        },
        {
          id: "01JKRRSM70E9F6N36TRX70JDY6",
          storeName:"始发旗舰店",
          storeAbbr: "始发*天猫"
        },
        {
          id: "01JKRRSM71SFYQKPG05P3VTKDW",
          storeName:"搜途办公专营店",
          storeAbbr: "搜途*天猫"
        },
        {
          id: "01JKRRSM72J6Z04P5XPBT8C29V",
          storeName:"屹呈旗舰店",
          storeAbbr: "屹呈*天猫"
        },
        {
          id: "01JKRRSM71JV9HAFXDPPBZ5AJZ",
          storeName:"哲众旗舰店",
          storeAbbr: "哲众3C店*天猫"
        },
        {
          id: "01JKRRSM71P4040WGM79P66HVM",
          storeName:"智呈旗舰店",
          storeAbbr: "智呈*天猫"
        },
        {
          id: "01JKRRSM72NZRQNYFA9R1KYC5X",
          storeName:"中奥晋呈旗舰店",
          storeAbbr: "中奥晋呈*天猫"
        },
        {
          id: "01JKRRSM73QE8RCPBJ9BHFXYWS",
          storeName:"中慧达旗舰店",
          storeAbbr: "中慧达*天猫"
        },
        {
          id: "01JKRRSM73Q0ET93B0WB2A1KZF",
          storeName:"中利呈旗舰店",
          storeAbbr: "中利呈*天猫"
        }
      ],
      //海报事业部固定店铺列表
      storeListHB: [
        {
          id: "01JKRRSM71QGNRHC3V8DTWX40T",
          storeName:"素锦留旗舰店",
          storeAbbr: "素锦留*天猫"
        },
        {
          id: "01JKRRSM71HTB3HFCY5XFTQG5N",
          storeName:"jnjb2008",
          storeAbbr: "一店墙贴店*淘宝"
        },
        {
          id: "01JKRRSM720PBX06AN46ZSA7QM",
          storeName:"宝菁旗舰店",
          storeAbbr: "宝菁*天猫"
        },
        {
          id: "01JKRRSM71MY7TXAADW0C462CK",
          storeName:"董东东2013",
          storeAbbr: "二店*淘宝"
        },
        {
          id: "01JKRRSM72PDCW57EQG6R8PM8H",
          storeName:"格莱美海报工厂",
          storeAbbr: "四店海报店*淘宝"
        },
        {
          id: "01JKRRSM71JABVAX2E6B24AK0C",
          storeName:"世格创意贴饰",
          storeAbbr: "世格*淘宝"
        },
        {
          id: "01JKRRSM71XCDKYFTFK0PADK08",
          storeName:"翔启扬旗舰店",
          storeAbbr: "翔启扬*天猫"
        },
        {
          id: "01JKRRSM71RFA85ACX1D1NNNPV",
          storeName:"星耀创意贴饰",
          storeAbbr: "星耀*淘宝"
        },
        {
          id: "01JKRRSM7267ZJ7EM6YDSHZDRP",
          storeName:"益讯旗舰店",
          storeAbbr: "益讯*天猫"
        },
        {
          id: "01JKRRSM71X2PYYQKW7F9CME86",
          storeName:"雨恋冰纯旗舰店",
          storeAbbr: "雨恋冰纯*天猫"
        },
        {
          id: "01JKRRSM71H75MAQW9R3DZB756",
          storeName:"哲众旗舰店",
          storeAbbr: "哲众海报店*天猫"
        },
        {
          id: "01JKRRSM71Y05N0HJ8SF7YPTG8",
          storeName:"哲众旗舰店",
          storeAbbr: "哲众墙贴店*天猫"
        },
        {
          id: "01JKRRSM71553YV26PVW0WHV4A",
          storeName:"智宏汇旗舰店",
          storeAbbr: "智宏汇*天猫"
        },
        {
          id: "01JYQQZ6GGVX82WRPYH6WQBD89",
          storeName:"中墨艺海旗舰店",
          storeAbbr: "中墨艺海*天猫"
        },
        {
          id: "01JKRRSM71HTB3HFCY5XFTQG5N",
          storeName:"jnjb2008",
          storeAbbr: "一店海报店*淘宝"
        },
      ],
      //商品标签文件上传路径
      goodsLabelAction:process.env.VUE_APP_BASE_API+"/business/goodsLabel/importData",
    }
  },
  created() {
    this.getUserInfo();
  },
  methods: {
    //获取店铺配置列表
    getUserInfo(){
      getConfigDetailByType({configType:1}).then(response => {
        this.storeList=response.data
        this.goodsUploadData.goodsStoreId=this.storeList[0].id;
        this.wholeUploadData.wholeStoreId=this.storeList[0].id;
        this.unUploadData.unStoreId=this.storeList[0].id;
      })
    },
    handleClick(tab, event) {
      if (tab.index==="0"){
        this.goodsFileList=[];
        this.goodsUploadData.goodsStoreId=this.storeList[0].id;
        this.goodsUploadData.goodsSelectDate=null;
        this.goodsUploadData.goodsFileHash=null;
      }else if (tab.index==="1"){
        this.wholeFileList=[];
        this.wholeUploadData.wholeStoreId=this.storeList[0].id;
        this.wholeUploadData.wholeSelectDate=null;
        this.wholeUploadData.wholeFileHash=null;
      }else if (tab.index==="2"){
        this.unFileList=[];
        this.unUploadData.unStoreId=this.storeList[0].id;
        this.unUploadData.unSelectDate=null;
        this.unUploadData.unFileHash=null;
      }else if (tab.index==="3"){
        console.log("上新")
      }
    },
    //商品指标店铺选择
    goodsStoreIdChange: function (storeId) {
      this.goodsStoreIndex=this.storeList.findIndex(s => s.id === storeId)
    },
    //全站指标店铺选择
    wholeStoreIdChange: function (storeId) {
      this.wholeStoreIndex=this.storeList.findIndex(s => s.id === storeId)
    },
    //无界指标店铺选择
    unStoreIdChange: function (storeId) {
      this.unStoreIndex=this.storeList.findIndex(s => s.id === storeId)
    },
    //文件上传获取token
    gainGetToken(){
      return getToken()
    },
    //=================================商品指标上传Start======================================
    //商品指标文件上传校验
    async handleGoodsChange(file) {
      //文件上传完成
      if (file.response){
        return false
      }
      let fileStore = this.getSpecificBracketedContent(file.name, 1);
      let fileDate = this.getSpecificBracketedContent(file.name, 2);

      let selectStoreName;
      await getStoreMgmt(this.goodsUploadData.goodsStoreId).then(response => {
        selectStoreName=response.data.storeName
      })

      //校验文件店铺名和日期
      if (selectStoreName===fileStore&&this.goodsUploadData.goodsSelectDate===this.conversionDate(fileDate)){

        //获取文件哈希值校验文件是否已上传
        this.getFileHash(file).then(res => {
          this.goodsUploadData.goodsFileHash=res
          this.$refs.goodsUpload.submit();
        })
      }else {
        this.$message({
          message: '店铺和日期与上传文件不符，请核实',
          type: 'warning'
        });
        this.$refs.goodsUpload.clearFiles();
      }
    },
    //上传加载
    handleGoodsLoading(){
      this.uploadLoad = this.$loading({
        lock: true,
        text: '数据上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    //商品数据文件上传后的回调
    handleGoodsUploadMessage(res, file){
      //清空文件集合
      this.$refs.goodsUpload.clearFiles();
      this.uploadLoad.close();
      if (res.code === 200) {
        this.$message({
          showClose: true,
          message: '数据上传成功',
          type: 'success'
        });
        //循环切换到下一个店铺
        this.goodsStoreIndex=(this.goodsStoreIndex+1)%this.storeList.length;
        this.goodsUploadData.goodsStoreId=this.storeList[this.goodsStoreIndex].id;
      }else if (res.code === 500) {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        });
      }
    },
    //=================================商品指标上传End======================================
    //=================================全站推指标上传Start======================================
    //全站推指标文件上传校验
    async handleWholeChange(file) {
      //文件上传完成
      if (file.response){
        return false
      }
      let fileStore = this.getSpecificBracketedContent(file.name, 1);
      let fileDate = this.getSpecificBracketedContent(file.name, 2);

      let selectStoreName;
      await getStoreMgmt(this.wholeUploadData.wholeStoreId).then(response => {
        selectStoreName=response.data.storeName
      })

      //校验文件店铺名和日期
      if (selectStoreName===fileStore&&this.wholeUploadData.wholeSelectDate===this.conversionDate(fileDate)){

        //获取文件哈希值校验文件是否已上传
        this.getFileHash(file).then(res => {
          this.wholeUploadData.wholeFileHash=res
          this.$refs.wholeUpload.submit();
        })
      }else {
        this.$message({
          message: '店铺和日期与上传文件不符，请核实',
          type: 'warning'
        });
        this.$refs.wholeUpload.clearFiles();
      }
    },
    //上传加载
    handleWholeLoading(){
      this.uploadLoad = this.$loading({
        lock: true,
        text: '数据上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    //全站推数据文件上传后的回调
    handleWholeUploadMessage(res, file){
      //清空文件集合
      this.$refs.wholeUpload.clearFiles();
      this.uploadLoad.close();
      if (res.code === 200) {
        this.$message({
          showClose: true,
          message: '数据上传成功',
          type: 'success'
        });
        //循环切换到下一个店铺
        this.wholeStoreIndex=(this.wholeStoreIndex+1)%this.storeList.length;
        this.wholeUploadData.wholeStoreId=this.storeList[this.wholeStoreIndex].id;
      }else if (res.code === 500) {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        });
      }
    },
    //=================================全站推指标上传End======================================
    //=================================无界指标上传Start======================================
    //无界指标文件上传校验
    async handleUnChange(file) {
      //文件上传完成
      if (file.response){
        return false
      }
      let fileStore = this.getSpecificBracketedContent(file.name, 1);
      let fileDate = this.getSpecificBracketedContent(file.name, 2);

      let selectStoreName;
      await getStoreMgmt(this.unUploadData.unStoreId).then(response => {
        selectStoreName=response.data.storeName
      })

      //校验文件店铺名和日期
      if (selectStoreName===fileStore&&this.unUploadData.unSelectDate===this.conversionDate(fileDate)){

        //获取文件哈希值校验文件是否已上传
        this.getFileHash(file).then(res => {
          this.unUploadData.unFileHash=res
          this.$refs.unUpload.submit();
        })
      }else {
        this.$message({
          message: '店铺和日期与上传文件不符，请核实',
          type: 'warning'
        });
        this.$refs.unUpload.clearFiles();
      }
    },
    //上传加载
    handleUnLoading(){
      this.uploadLoad = this.$loading({
        lock: true,
        text: '数据上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    //无界数据文件上传后的回调
    handleUnUploadMessage(res, file){
      //清空文件集合
      this.$refs.unUpload.clearFiles();
      this.uploadLoad.close();
      if (res.code === 200) {
        this.$message({
          showClose: true,
          message: '数据上传成功',
          type: 'success'
        });
        //循环切换到下一个店铺
        this.unStoreIndex=(this.unStoreIndex+1)%this.storeList.length;
        this.unUploadData.unStoreId=this.storeList[this.unStoreIndex].id;
      }else if (res.code === 500) {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        });
      }
    },
    //=================================无界指标上传End======================================
    //上新日期文件上传后的回调
    handleUpNewDateUploadMessage(res, file){
      //清空文件集合
      this.$refs.upNewDateUpload.clearFiles();
      this.uploadLoad.close();
      if (res.code === 200) {
        this.$message({
          showClose: true,
          message: '数据上传成功',
          type: 'success'
        });
      }else if (res.code === 500) {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        });
      }
    },
    /** 导出无上新日期按钮操作 */
    handleNoUpNewDateExport() {
      exportNoUpNewDateExcel()
    },
    //商品标签件上传后的回调
    handleGoodsLabelUploadMessage(res, file){
      //清空文件集合
      this.$refs.goodsLabelUpload.clearFiles();
      this.uploadLoad.close();
      if (res.code === 200) {
        this.$message({
          showClose: true,
          message: '数据上传成功',
          type: 'success'
        });
      }else if (res.code === 500) {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        });
      }
    },
    //商品标签上传加载
    handleGoodsLabelLoading(){
      this.uploadLoad = this.$loading({
        lock: true,
        text: '数据上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    //获取上传文件名【】中内容
    getSpecificBracketedContent(str, pairIndex) {
      const regex = /【(.*?)】/g;
      let match;
      let content = null;

      for (let i = 0; i < pairIndex; i++) {
        match = regex.exec(str);
        if (!match) {
          break; // 如果没有足够的匹配项，退出循环
        }
        // 对于我们关心的那一对，保存其内容
        if (i === pairIndex - 1) {
          content = match[1];
        }
      }

      return content;
    },
    //获取文件哈希值
    getFileHash(file) {
      return new Promise((resolve, reject) => {
        let fileHash;
        const fileReader = new FileReader();
        const spark = new SparkMD5.ArrayBuffer();

        // 获取文件二进制数据
        fileReader.readAsArrayBuffer(file.raw);

        fileReader.onload = (e) => {
          try {
            spark.append(e.target.result);
            fileHash = spark.end();
            resolve(fileHash); // 使用resolve返回哈希值
          } catch (error) {
            reject(error); // 在发生错误时拒绝Promise
          }
        };

        fileReader.onerror = (error) => {
          reject(error); // 处理文件读取错误
        };
      });
    },
    //转换日期格式
    conversionDate(dateStr) {
      // 正则表达式匹配不同格式的日期字符串
      const regex = /(\d{4})[/-]?(\d{1,2})[/-]?(\d{1,2})/;
      const match = dateStr.match(regex);

      if (match) {
        const [, year, month, day] = match;

        // 确保月份和日期都是两位数
        const formattedMonth = String(parseInt(month, 10)).padStart(2, '0');
        const formattedDay = String(parseInt(day, 10)).padStart(2, '0');

        // 返回格式化后的日期字符串
        return `${year}-${formattedMonth}-${formattedDay}`;
      } else {
        this.$message({
          message: '文件日期格式错误',
          type: 'warning'
        });
      }
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-upload-dragger{
  width: 550px;
  height: 250px;
}

.font-color{
  color: #409eff;
}
</style>
